package tech.mhuang.pacebox.springboot.payment.wechat.util;

import jakarta.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付工具类
 *
 * @author mhuang
 * @since 1.0.0
 */
public class PayUtil {

    public static String requestUrl(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (StringUtil.isNotBlank(queryString)) {
            return request.getRequestURL().append("?").append(request.getQueryString()).toString();
        }
        return request.getRequestURL().toString();
    }

    public static Map<String, String> parseXml(String request) {
        Map<String, String> map = null;
        try {
            // 读取输入流
            Document document = DocumentHelper.parseText(request);

            // 得到xml根元素
            Element root = document.getRootElement();

            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            map = CollectionUtil.capacity(HashMap.class, elementList.size());
            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
